// pages/user-center/manage-team/manage-team-info/manage-team-info.js
const app = getApp();
const config = require('../../../../utils/config');
const request = require('../../../../utils/request');

Page({

  /**
   * 页面的初始数据
   */
  data: {
    colorTheme: app.globalData.colorTheme,
    teamId: -1,
    teamInfo: [],
    checkbox: [],
    choosedTags: [],
    recruitment: {}
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      teamId: options.teamId
    });
    this.getTeamPageInfo();
  },

  /**
   * 获取团队信息
   */
  getTeamPageInfo: function() {
    let that = this;
    let teamId = this.data.teamId;
    let url = config.SERVER_URL + 'index/team/' + teamId;
    wx.showLoading({
      title: '加载ing'
    })
    request.requestGetApi(url, {}, {}, 'application/json').then(res=>{
      if(res.status === config.STATUS_OK){
        that.setData({
          teamInfo: res.data
        });
      }
    }).catch(err=>{
      app.failFun(err);
    }).finally(res=>{
      app.completeFun(res);
    });
  },

  /**
   * 更新logo图片
   */
  updateLogoImage: function (e) {
    let token = wx.getStorageSync('token');
    let that = this;
    wx.chooseImage({
      success (res) {
        const tempFilePaths = res.tempFilePaths;
        wx.showLoading({
          title: '上传ing'
        });
        wx.uploadFile({
          url: config.SERVER_URL + 'teams/updateTeamsLogo',
          filePath: tempFilePaths[0],
          name: 'logo',
          formData:{
            'teamsId': that.data.teamId,
          },
          header: {
            'UT-Token': token
          },
          success (res) {
            if (res.statusCode != config.STATUS_OK) {
              app.failFun(res, that);
            }
            that.getTeamPageInfo();
            wx.hideLoading();
            wx.showToast({
              title: "更新团队头像成功！"
            });
          }
        })
      }
    })
  },

  /**
   * 更新名称
   */
  updateTeamName(e){
    let params = e.detail.value;
    params.id = this.data.teamId;
    let token = wx.getStorageSync('token');
    wx.showLoading({
      title: '保存ing'
    });
    let url = config.SERVER_URL + 'teams/updateTeamsBaseInfo';
    request.requestPostApi(url, token, params, 'application/json').then(res=>{
      if (res.status === config.STATUS_OK) {
        this.getTeamPageInfo();
        wx.showToast({
          title: '保存成功！',
          icon: 'success',
          duration: 2000
        })
      }
    }).catch((err) => {
      app.failFun(err);
    }).finally((res) => {
      app.completeFun(res);
    })
    this.hideModal();
  },

  /**
   * 更新名称、描述和状态信息
   */
  saveTeamSimpleInfo(e){
    let params = e.detail.value;
    params.id = this.data.teamId;
    params.status = params.status ? 1 : 0;
    console.log(params);
    let token = wx.getStorageSync('token');
    wx.showLoading({
      title: '保存ing'
    });
    let url = config.SERVER_URL + 'teams/updateTeamsBaseInfo';
    request.requestPostApi(url, token, params, 'application/json').then(res=>{
      if (res.status === config.STATUS_OK) {
        this.getTeamPageInfo();
        wx.showToast({
          title: '保存成功！',
          icon: 'success',
          duration: 2000
        })
      }
    }).catch((err) => {
      app.failFun(err);
    }).finally((res) => {
      app.completeFun(res);
    })
    this.hideEdit();
  },

  /**
   * 更新状态信息
   */
  updateTeamStatus(e) {
    let team = this.data.teamInfo;
    let params = {
      detail:{
        value:{
          description: team.description,
          status: e.detail.value
        }
      }
    }
    console.log(params)
    this.saveTeamSimpleInfo(params);
  },

  /**
   * 服务器获取标签
   */
  showTagsModal: function (e) {
    let that = this;
    let teamTags = this.data.teamInfo.tags;
    let url = config.SERVER_URL + 'tags/listAllTags'
    wx.showLoading({
      title: '加载ing...'
    })
    request.requestGetApi(url, {}, {}, 'application/json').then(res => {
      if (res.status === config.STATUS_OK) {
        let allTags = res.data;
        for (let i = 0; i < teamTags.length; i++) {
          allTags.find(function (value, index) {
            if (value.id == teamTags[i].id) {
              allTags[index]['checked'] = true;
            }
          });
        }
        let choosedTags = [];
        for (let i = 0; i < teamTags.length; i++) {
          choosedTags.push(teamTags[i].id);
        }
        this.setData({
          checkbox: allTags,
          choosedTags: choosedTags
        });
      }
    }).catch(err => {
      app.failFun(err)
    }).finally((res) => {
      app.completeFun(res)
    })
    this.showModal(e);
  },

  /**
   * 点中标签
   */
  chooseTag: function (e) {
    let id = e.currentTarget.dataset.value;
    let allTags = this.data.checkbox;
    let choosedTags = this.data.choosedTags;
    allTags.find(function (value, index) {
      if (id == value.id) {
        allTags[index].checked = !allTags[index].checked;
        if (allTags[index].checked) {
          choosedTags.push(allTags[index].id);
        }else{
          choosedTags.pop();
        }
        if (choosedTags.length > 3) {
          allTags[index].checked = false;
          choosedTags.pop();
          wx.showModal({
            title: '提示',
            content: '标签数量不能 > 3',
          })
        }
      }
    });
    this.setData({
      checkbox: allTags,
      choosedTags: choosedTags,
    })
  },

  /**
   * 保存标签
   */
  saveTeamTags: function (e) {
    let that = this;
    let choosedTags = this.data.choosedTags;
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL + 'teams/saveTeamsTags?teamsId=' + this.data.teamId;
    wx.showLoading({
      title: '保存ing...'
    });
    request.requestPostApi(url, token, choosedTags, 'application/json').then(res => {
      if (res.status === config.STATUS_OK) {
        this.hideModal();
        this.getTeamPageInfo();
        wx.showToast({
          title: '保存成功',
          icon: 'success',
          duration: 2000
        })
      }
    })
  },

  /**
   * 保存职位信息
   */
  saveRecruitment(e) {
    let params = e.detail.value;
    params.teamId = this.data.teamId + "";
    if(!params.id){
      delete params.id;
    };
    let token = wx.getStorageSync('token');
    wx.showLoading({
      title: '保存ing'
    });
    let url = config.SERVER_URL + 'teams/saveTeamsRecruitment';
    request.requestPostApi(url, token, params, 'application/json').then(res=>{
      if (res.status === config.STATUS_OK) {
        this.getTeamPageInfo();
        this.data.recruitment = {};
        wx.showToast({
          title: '添加成功！',
          icon: 'success',
          duration: 2000
        });
      };
    }).catch((err) => {
      app.failFun(err);
    }).finally((res) => {
      app.completeFun(res);
    });
    this.hideModal();
  },

  /**
   * 更改职位信息
   */
  editRecruitment(e){
    let index = e.currentTarget.dataset.target;
    this.setData({
      recruitment: this.data.teamInfo.recruitments[index],
      modalName: 'recruitmentModal'
    });
  },

  /**
   * 删除职位信息
   */
  deleteRecruitment(e){
    let index = e.currentTarget.dataset.index;
    let recruitmentId = e.currentTarget.dataset.target;
    let teamInfo = this.data.teamInfo;
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL + `teams/remove/recruitment/${this.data.teamId}/${recruitmentId}`;
    wx.showLoading({
      title: '操作ing',
    })
    request.requestPostApi(url, token, {}, 'application/json').then(res=>{
      if(res.status === config.STATUS_OK){
        teamInfo.recruitments.splice(index, 1);
        this.setData({
          teamInfo: teamInfo
        })
        wx.showToast({
          title: '操作成功！',
        });
      }
    }).catch((err) => {
      app.failFun(err);
    }).finally((res) => {
      app.completeFun(res);
    });
  },

  /**
   * 预选队长
   */
  selectMember(e){
    this.setData({
      memberUid: e.detail.value
    });
  },

  /**
   * 保存该成员为队长
   */
  saveLeader(e){
    if(!this.data.memberUid){
      wx.showToast({
        title: '请选择一名队员',
        icon: 'none',
        duration: 1500
      });
      return;
    }
    let that = this;
    let token = wx.getStorageSync('token');
    let url = config.SERVER_URL + 'teams/transferLeader?targetUid=' + this.data.memberUid + '&teamId=' + this.data.teamId;
    wx.showLoading({
      title: '操作ing'
    });
    request.requestPostApi(url, token, {}, 'application/json').then(res => {
      if(res.status === config.STATUS_OK){
        that.hideModal();
        wx.showToast({
          title: res.message,
          icon: 'success',
          duration: 2000,
          success: ()=>{
            wx.navigateBack({
              delta: 1
            });
          }
        });
      }
    }).catch((err) => {
      app.failFun(err);
    }).finally((res) => {
      app.completeFun(res);
    });
  },

  /**
   * 开除团队成员
   */
  deleteModal(e){
    if(e.currentTarget.dataset.user.role === '队长'){
      return;
    }
    let that = this;
    let token = wx.getStorageSync('token');
    wx.showModal({
      title: '移除队友',
      content: '确定要移除该队友吗？',
      confirmText: '确定',
      confirmColor: '#3CC51F',
      success: (result) => {
        if(result.confirm){
          let uid = e.currentTarget.dataset.user.uid;
          let params = {
            mode: 1,
            teamsId: this.data.teamId,
            firedUid: uid
          }
          let url = config.SERVER_URL + 'teams/leave';
          request.requestPostApi(url, token, params, 'application/json').then(res => {
            if(res.status === config.STATUS_OK){
              that.getTeamPageInfo();
              wx.showToast({
                title: res.message,
                icon: 'success',
                duration: 2000
              });
            }
          }).catch(err => {
            app.failFun(err);
          });
        }
      }
    });
  },

  /**
   * 解散队伍
   */
  disBand(){
    let that = this;
    wx.showModal({
      title: '解散队伍',
      content: '确定要解散该队伍吗？',
      confirmText: '确定',
      confirmColor: '#e54d42',
      success: (result) => {
        if(result.confirm){
          let url = config.SERVER_URL + 'teams/disband/' + that.data.teamId;
          let token = wx.getStorageSync('token');
          request.requestPostApi(url, token, {}, 'application/json').then(res => {
            if(res.status === config.STATUS_OK){
              wx.showToast({
                title: res.message,
                icon: 'success',
                duration: 2000
              });
              wx.navigateBack({
                delta: 1
              })
            }
          }).catch(err => {
            app.failFun(err);
          });
        }
      }
    });
  },

  /**
   * 模态框
   */
  showModal (e) {
    let modalName = e.currentTarget.dataset.target;
    this.setData({
      modalName: modalName
    })
  },
  hideModal (e) {
    this.setData({
      modalName: null,
      recruitment: {}
    })
  },

  /**
   * 编辑框
   */
  showEdit (e) {
    if (this.data.editName == 'wait') {
      this.data.editName = null;
      return;
    }
    this.setData({
      editName: e.currentTarget.dataset.target
    });
  },
  hideEdit (e) {
    this.setData({
      editName: 'wait'
    })
  },

  /**
   * 查看用户展示页
   */
  goUserShowPage: function(e) {
    let uid = e.currentTarget.dataset.user.uid;
    wx.navigateTo({
      url: '/pages/user-show-info/user-show-info?uid=' + uid,
    })
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.getTeamPageInfo();

    wx.stopPullDownRefresh();
  },

  // ListTouch触摸开始
  ListTouchStart(e) {
    this.setData({
      ListTouchStart: e.touches[0].pageX
    })
  },

  // ListTouch计算方向
  ListTouchMove(e) {
    this.setData({
      ListTouchDirection: e.touches[0].pageX - this.data.ListTouchStart > 0 ? 'right' : 'left'
    })
  },

  // ListTouch计算滚动
  ListTouchEnd(e) {
    if (this.data.ListTouchDirection =='left'){
      this.setData({
        modalName: e.currentTarget.dataset.target
      })
    } else {
      this.setData({
        modalName: null
      })
    }
    this.setData({
      ListTouchDirection: null
    })
  },

})